package org.vgou.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

public class StrutsUtils {
	public static final String TEXT_TYPE = "text/plain";
	public static final String JSON_TYPE = "application/json";
	public static final String DEFAULT_ENCODING = "gb2312";

	/**
	 * 直接输出内容的辅助函数
	 * 
	 * @param content 返回的内容
	 */
	public static void render(final String contentType, final String content) {
		// 设置response的contentType和禁用缓存Header
		HttpServletResponse response = initResponse(contentType);
		try {
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 直接输出文本的辅助函数，用于简单的服务端验证
	 * 
	 * @param content 返回的内容
	 */
	public static void renderJson(final String content) {
		render(JSON_TYPE, content);
	}

	/**
	 * 直接输出Json的辅助函数
	 * 
	 * @param content 返回的内容
	 */
	public static void renderText(final String jsonString) {
		render(JSON_TYPE, jsonString);
	}

	/**
	 *	简单的Response初始化辅助函数 
	 */
	private static HttpServletResponse initResponse(final String contentTpye) {
		// 设置response的contentType
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType(TEXT_TYPE + ";charset=" + DEFAULT_ENCODING);
		// 禁止客户端缓存
		StrutsUtils.setNoCacheHeader(response);
		return response;
	}

	/**
	 * 设置禁止缓存的Header.
	 */
	public static void setNoCacheHeader(HttpServletResponse response) {
		// Http 1.0 header
		response.setDateHeader("Expires", 1L);
		response.addHeader("Pragma", "no-cache");
		// Http 1.1 header
		response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
	}

	/**
	 * 获取HttpSession的帮助函数
	 */
	public static HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}

	/**
	 * 获取HttpSession的帮助函数
	 */
	public static HttpSession getSession(boolean isNew) {
		return ServletActionContext.getRequest().getSession(isNew);
	}

	/**
	 * 获取HttpRequest的帮助函数
	 */
	public static HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 取得HttpRequest中Parameter的简化方法.
	 */
	public static String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	/**
	 * 获取HttpResponse的帮助函数
	 */
	public static HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 取得HttpSession中Attribute的帮助函数.
	 */
	public static Object getSessionAttribute(String name) {
		HttpSession session = getSession(false);
		return (session != null ? session.getAttribute(name) : null);
	}
}
